import { login, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
// import { resetRouter } from "@/router";


const state = {
  token: getToken(), // token 
  userInfo:{}  // 用户资料
}

const mutations = {
  // 设置 token
  setToken (state, data) {
    state.token = data;
    setToken(data);

  },
  SET_TOKEN: (state, token) => {
    console.log(token);
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  // 设置用户资料
  setUserInfo (state, data) {
    state.userInfo = data;
  },
  // 删除清空 token
  removeToken (state) {
    state.token = null
    removeToken()
  }
};

const actions = {
  // 登陆的操作，将token存储到state和cookie
  async login (context, datas) {
    const { token } = await login(datas);
    context.commit("setToken", token);
    // const { account, password } = userInfo;
    // const data = await login({ account: account.trim(), password: password });
    // commit("SET_TOKEN", data.token);
    // setToken(data.token);
  },

  // 获取用户资料
  async getInfo ({ commit }) {
    const { userinfo } = await getInfo();
    commit("setUserInfo", userinfo);
    // let data = await getInfo();
    // commit("SET_NAME", data.name);
    // commit("SET_AVATAR", data.avatar);
    // return data;
  },

  // 退出功能
  logout ({ commit }) {
    commit('removeToken')
    commit('setUserInfo', {})
  }
  // // user logout
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token)
  //       .then(() => {
  //         removeToken(); // must remove  token  first
  //         resetRouter();
  //         commit("RESET_STATE");
  //         resolve();
  //       })
  //       .catch((error) => {
  //         reject(error);
  //       });
  //   });
  // },

  // // remove token
  // resetToken({ commit }) {
  //   return new Promise((resolve) => {
  //     removeToken(); // must remove  token  first
  //     commit("RESET_STATE");
  //     resolve();
  //   });
  // },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
